import random

from bson.objectid import ObjectId
from pymongo import MongoClient
from flask import request, url_for
from flask import render_template
from flask import Flask, jsonify
from flask import make_response

import jieba.posseg as pseg
import pandas as pd
import datetime
import pymongo
import difflib
import pprint
import socket

import difflib
import time
import jieba
import json
import sys
import re

# with open('/Users/xuchaosheng/NLP/total_posts2', 'r') as f:
#     total_posts = json.load(f)

client = MongoClient('47.104.130.19', 27017)
db = client['knx_posts_db']
offical_posts_coll = db['offical_posts_coll']

app = Flask(__name__)


@app.route('/functional_divide')
def functional_divide():
    return render_template('functional_divide.html')


@app.route('/knx/load_train_data')
def load_train_data():
    data = list(offical_posts_coll.aggregate([{'$sample': {'size': 1}}]))
    del data[0]['_id']
    del data[0]['stime']

    return json.dumps({
        'success': True,
        # 'data': random.sample(total_posts, 1)
        'data': data
    })


@app.route('/knx/tagging_train_data')
def tagging_train_data():
    func = request.args.get('func', '').strip()
    desc = request.args.get('desc', '').strip()

    if func == '' or desc == '':
        return json.dumps({
            'success': False
        })

    with open('func_train_data/' + str(time.time()), 'w', encoding = 'utf-8') as  f:
        f.write('func:' + func + '\n')
        f.write('desc:' + desc)

    return json.dumps({
        'success': True
    })


with app.test_request_context():
    url_for('static', filename = '*')

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0', port = 8086)
